<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="套餐名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择套餐类型" filterable clearable style="width: 100%;">
          <el-option
            v-for="dict in dict.type.combo_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区域" prop="region">
        <region-cascader
          :multiple = true
          v-model="queryParams.region"
          placeholder="请选择区域"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['demo:combo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['demo:combo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['demo:combo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['demo:combo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="comboList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="套餐名称" align="center" prop="name" />
      <el-table-column label="套餐类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.combo_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="区域" align="center" prop="region">
        <template slot-scope="scope">
          {{ formatRegionDisplay(scope.row.region) }}
        </template>
      </el-table-column>
      <el-table-column label="套餐价格" align="center" prop="price" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['demo:combo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['demo:combo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改套餐管理抽屉 -->
    <el-drawer :title="title" :visible.sync="open" direction="ltr" size="50%" :before-close="cancel">
      <div class="drawer-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-divider content-position="left">基本信息</el-divider>
          <el-form-item label="绑定文章" prop="articleId">
            <el-select v-model="form.articleId" placeholder="请选择绑定文章" style="width: 100%;">
              <el-option
                v-for="item in articleList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="套餐名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入套餐名称" />
          </el-form-item>
          <el-form-item label="套餐类型" prop="type">
            <el-select v-model="form.type" filterable clearable placeholder="请选择套餐类型" style="width: 100%;">
              <el-option
                v-for="dict in dict.type.combo_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="套餐介绍" prop="introduction">
            <el-input v-model="form.introduction" type="textarea" :autosize="{ minRows: 2, maxRows: 6}" placeholder="请输入套餐介绍" />
          </el-form-item>
          
          <el-divider content-position="left">价格与区域</el-divider>
          <el-form-item label="套餐价格" prop="price">
            <el-input-number v-model="form.price" placeholder="请输入套餐价格" controls-position="right" :precision="2" :step="0.1" :min="0" style="width: 100%;"></el-input-number>
          </el-form-item>
          <el-form-item label="区域" prop="region">
            <region-cascader
              v-model="form.region"
              :multiple = true
              placeholder="请选择区域"
            />
          </el-form-item>
          <el-form-item label="运费" prop="shippingCost">
            <el-input-number v-model="form.shippingCost" placeholder="请输入运费" controls-position="right" :precision="2" :step="0.1" :min="0" style="width: 100%;"></el-input-number>
          </el-form-item>
          
          <el-divider content-position="left">时间设置</el-divider>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker clearable
              v-model="form.startTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择开始时间"
              style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker clearable
              v-model="form.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择结束时间"
              style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="数量" prop="num">
            <el-input-number v-model="form.num" placeholder="请输入数量" controls-position="right" :precision="0" :step="1" :min="1" style="width: 100%;"></el-input-number>
          </el-form-item>
          
          <el-divider content-position="left">套餐配置</el-divider>
          <el-form-item label="产品" prop="comboProduct">
            <div class="product-list">
              <div v-for="(product, index) in form.comboProduct" :key="index" class="product-item">
                <el-select 
                  v-model="product.productId" 
                  filterable 
                  placeholder="请选择产品" 
                  style="width: 75%; margin-right: 1%;"
                  @change="handleProductChange(product)"
                >
                  <el-option
                    v-for="p in productList"
                    :key="p.id"
                    :label="p.name + '('+ p.alias +')' + ' ￥' + p.price + ' 规格：' +p.specification"
                    :value="p.id">
                  </el-option>
                </el-select>
                <el-input-number 
                  v-model="product.num" 
                  placeholder="数量" 
                  controls-position="right" 
                  :precision="0" 
                  :step="1" 
                  :min="1" 
                  style="width: 24%;"
                ></el-input-number>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  circle 
                  @click="removeProductItem('comboProduct', index)" 
                  style="margin-left: 10px;"
                ></el-button>
              </div>
              <el-button type="primary" icon="el-icon-plus" @click="addProductItem('comboProduct')">添加产品</el-button>
            </div>
          </el-form-item>
          <el-form-item label="赠品" prop="freeGift">
            <div class="product-list">
              <div v-for="(gift, index) in form.freeGift" :key="index" class="product-item">
                <el-select 
                  v-model="gift.productId" 
                  filterable 
                  placeholder="请选择赠品" 
                  style="width: 75%; margin-right: 1%;"
                  @change="handleProductChange(gift)"
                >
                  <el-option
                    v-for="p in productList"
                    :key="p.id"
                    :label="p.name + '('+ p.alias +')' + ' ￥' + p.price + ' 规格：' +p.specification"
                    :value="p.id">
                  </el-option>
                </el-select>
                <el-input-number 
                  v-model="gift.num" 
                  placeholder="数量" 
                  controls-position="right" 
                  :precision="0" 
                  :step="1" 
                  :min="1" 
                  style="width: 24%;"
                ></el-input-number>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  circle 
                  @click="removeProductItem('freeGift', index)" 
                  style="margin-left: 10px;"
                ></el-button>
              </div>
              <el-button type="primary" icon="el-icon-plus" @click="addProductItem('freeGift')">添加赠品</el-button>
            </div>
          </el-form-item>
          
          <el-divider content-position="left">封面图片</el-divider>
          <el-form-item label="封面图片" prop="image">
            <image-upload v-model="form.image" :limit="1" />
          </el-form-item>
        </el-form>
        <div class="drawer-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listCombo, getCombo, delCombo, addCombo, updateCombo } from "@/api/demo/combo";
import { listArticle } from "@/api/demo/article";
import { listProduct } from "@/api/demo/product";
import RegionCascader from "@/components/RegionCascader";
import regionData from '@/utils/regionData'; // 导入地区数据

export default {
  name: "Combo",
  dicts: ['combo_type'],
  components: {
    RegionCascader
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 套餐管理表格数据
      comboList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        introduction: null,
        price: null,
        region: null,
        startTime: null,
        endTime: null,
        num: null,
        type: null,
        image: null,
        comboProduct: null,
        shippingCost: null,
        freeGift: null,
      },
      // 表单参数
      form: {
        price: 0,
        shippingCost: 0,
        num: 1,
        comboProduct: [],
        freeGift: []
      },
      productList: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "请选择套餐类型", trigger: "change" }
        ],
        price: [
          { required: true, message: "套餐价格不能为空", trigger: "blur" },
          { type: 'number', min: 0, message: "套餐价格必须大于等于0", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "change" }
        ],
        num: [
          { required: true, message: "套餐数量不能为空", trigger: "blur" },
          { type: 'number', min: 1, message: "套餐数量必须大于等于1", trigger: "blur" }
        ]
      },
      regionOptions: regionData, // 添加地区数据
      articleList: [],
    };
  },
  created() {
    this.getList();
    this.getProductList();
  },
  methods: {
    getArticleList() {
      listArticle({pageNum:1,pageSize:1000}).then(response => {
        this.articleList = response.rows;
      });
    },
    /** 添加产品项 */
    addProductItem(type) {
      this.form[type].push({
        productId: '',
        num: 1
      });
    },
    
    /** 移除产品项 */
    removeProductItem(type, index) {
      this.form[type].splice(index, 1);
    },
    
    /** 处理产品选择变化 */
    handleProductChange(item) {
      // 这里可以添加额外的逻辑，比如根据产品ID获取产品信息等
      console.log('产品选择变化:', item);
    },
    
    /** 格式化区域显示 */
    formatRegionDisplay(region) {
      if (!region) return '-';
      
      try {
        // 如果region是字符串，尝试解析为数组
        let regionArray = region;
        if (typeof region === 'string') {
          regionArray = JSON.parse(region);
        }
        
        // 处理二维数组格式 [["140000","140100","140105"],["140000","140100","140106"]]
        if (Array.isArray(regionArray) && regionArray.length > 0) {
          // 判断是否是二维数组
          if (Array.isArray(regionArray[0])) {
            // 处理多个地区路径
            const regionNames = regionArray.map(path => {
              return this.getFullRegionName(path);
            });
            
            // 如果所有路径都相同（只显示一个），或者显示前几个用逗号分隔
            const uniqueNames = [...new Set(regionNames)];
            if (uniqueNames.length === 1) {
              return uniqueNames[0];
            } else {
              // 显示前3个，超过用等表示
              const displayNames = uniqueNames.slice(0, 3);
              return displayNames.join('、') + (uniqueNames.length > 3 ? ` 等${uniqueNames.length}个地区` : '');
            }
          } else {
            // 处理单个地区路径（一维数组）
            return this.getFullRegionName(regionArray);
          }
        }
        return '-';
      } catch (e) {
        console.error('区域数据解析失败:', e);
        // 如果解析失败，返回原始值
        return region || '-';
      }
    },

    /** 获取完整的地区名称 */
    getFullRegionName(codes) {
      if (!codes || !Array.isArray(codes) || codes.length === 0) return '';
      
      const names = [];
      let currentLevel = this.regionOptions;
      
      for (let i = 0; i < codes.length; i++) {
        const code = codes[i];
        const region = currentLevel.find(item => item.value === code);
        if (region) {
          names.push(region.label);
          currentLevel = region.children || [];
        } else {
          // 如果没有找到对应的地区，尝试直接使用编码
          names.push(code);
          break;
        }
      }
      
      return names.join(' / ');
    },
    /** 查询产品列表 */
    getProductList() {
      listProduct({pageNum:1,pageSize:1000}).then(response => {
        this.productList = response.rows;
      });
    },
    /** 查询套餐管理列表 */
    getList() {
      this.loading = true;
      listCombo(this.queryParams).then(response => {
        this.comboList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        introduction: null,
        price: 0,
        region: null,
        startTime: null,
        endTime: null,
        num: 1,
        type: null,
        image: null,
        comboProduct: [],
        shippingCost: 0,
        freeGift: [],
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.region = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 默认添加一个空的产品项
      this.form.comboProduct = [{ productId: '', num: 1 }];
      this.form.freeGift = [{ productId: '', num: 1 }];
      this.open = true;
      this.title = "添加套餐管理";
      this.getArticleList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCombo(id).then(response => {
      this.getArticleList();
        this.form = response.data;
        if(this.form.articleId!=null){
          this.form.articleId = this.form.articleId + ''
        }
        // 处理comboProduct字段的数据格式
        if (this.form.comboProduct) {
          if (typeof this.form.comboProduct === 'string') {
            try {
              this.form.comboProduct = JSON.parse(this.form.comboProduct);
            } catch (e) {
              console.error('解析comboProduct失败:', e);
              this.form.comboProduct = [];
            }
          }
        } else {
          this.form.comboProduct = [];
        }
        
        // 处理freeGift字段的数据格式
        if (this.form.freeGift) {
          if (typeof this.form.freeGift === 'string') {
            try {
              this.form.freeGift = JSON.parse(this.form.freeGift);
            } catch (e) {
              console.error('解析freeGift失败:', e);
              this.form.freeGift = [];
            }
          }
        } else {
          this.form.freeGift = [];
        }
        
        // 处理区域字段
        if (this.form.region && typeof this.form.region === 'string') {
          try {
            this.form.region = JSON.parse(this.form.region);
          } catch (e) {
            // 如果不是JSON格式，保持原样
          }
        }
        
        // 确保数组不为空，至少有一个项目
        if (this.form.comboProduct.length === 0) {
          this.form.comboProduct = [{ productId: '', num: 1 }];
        }
        if (this.form.freeGift.length === 0) {
          this.form.freeGift = [{ productId: '', num: 1 }];
        }
        
        this.open = true;
        this.title = "修改套餐管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保数字字段有默认值
          this.form.price = this.form.price || 0;
          this.form.shippingCost = this.form.shippingCost || 0;
          this.form.num = this.form.num || 1;
          
          // 过滤掉产品ID为空的项目
          const filteredComboProduct = this.form.comboProduct.filter(item => item.productId);
          const filteredFreeGift = this.form.freeGift.filter(item => item.productId);
          
          // 处理数据格式
          const submitData = { ...this.form };
          submitData.comboProduct = filteredComboProduct.length > 0 ? JSON.stringify(filteredComboProduct) : '';
          submitData.freeGift = filteredFreeGift.length > 0 ? JSON.stringify(filteredFreeGift) : '';
          submitData.region = submitData.region && submitData.region.length > 0 ? JSON.stringify(submitData.region) : '';

          if (submitData.id != null) {
            updateCombo(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCombo(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除套餐管理编号为"' + ids + '"的数据项？').then(function() {
        return delCombo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('demo/combo/export', {
        ...this.queryParams
      }, `combo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.drawer-content {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

.drawer-footer {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

.el-divider {
  margin: 30px 0 20px 0;
}

.el-form-item {
  margin-bottom: 20px;
}

.product-list {
  width: 100%;
}

.product-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

/* 为必填项添加红色星号 */
.el-form-item.is-required .el-form-item__label:before {
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}
</style>